package 树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author ssh
 * @date 2025/8/24
 * @description
 */
public class 二叉树的层序遍历 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res= new ArrayList<>();

        if(root==null){
            return res;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> ret= new ArrayList<>();
            int currentsize=queue.size();
            for(int i=0;i<currentsize;i++){
                TreeNode node=queue.poll();
                ret.add(node.val);
                if(node.left!=null){
                    queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }

            }
            res.add(ret);

        }
        return res;
    }

    public static void main(String[] args) {
        // 测试代码
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        二叉树的层序遍历 solution = new 二叉树的层序遍历();
        List<List<Integer>> result = solution.levelOrder(root);
        System.out.println(result); // 输出: [[3], [9, 20], [15, 7]]
    }
}
